<?php

namespace App\Model;

use App\BaseModel;
use App\Helpers\Helpers;
use App\Helpers\VisitTrait;
use Illuminate\Support\Facades\DB;

class Article extends BaseModel
{
    use VisitTrait;

    protected $table = "cms_article";

    protected $fillable = ['title','author','column_id','abstract','type','video_path',
        'video_type','online','online_at','offline_at','content','state','user_id','weight',
        'pv','uv','collection_quantity','feature','updater','creator','weixin_id','showHeadPic'];

    protected $appends = ['column_name'];

    public function user()
    {
        return $this->belongsTo('App\User','user_id','id');
    }

    public function column()
    {
        return $this->belongsTo('App\Model\ArticleColumn','column_id','id');
    }

    public function covers()
    {
        return $this->belongsToMany('App\Model\Resource','sys_resource_table',
            'obj_id','resource_id')->wherePivot('obj_type','article_cover');
    }

    public function getColumnNameAttribute()
    {
        return $this->column ? $this->column->name:'';
    }

    public function hasCollect()
    {
        return $this->belongsToMany('App\User','t_user_article_collections','article_id','user_id');
    }

    public function userHasCollect()
    {
        return $this->hasOne('App\Model\ArticleCollection','article_id','id')
            ->where('t_user_article_collections.user_id','=',$this->loginUser()?$this->loginUser()->id:0);
    }

    public function beforeSave($input=null)
    {

        if($this->online != $this->getOriginal('online')) {
            if ($this->online == "yes") {
                $this->online_at = Helpers::now();
            }
            if ($this->online == "no") {
                $this->offline_at =  Helpers::now();
            }
        }

        return true;
    }

    public static function saveCovers($article_id,$covers,$obj_type="article_cover", $type = '')
    {
        if (is_array($covers) && $article_id) {

            DB::table('sys_resource_table')->where('obj_id','=',$article_id)
                ->where('obj_type','=',$obj_type)->delete();

            foreach ($covers as $v) {

                $r = new Resource();
                $r->path = $v;
                $r->uploadType = "qiniu";
                $r->type = $type;
                $r->save();

                $m = new ResourceTable();
                $m->obj_id = $article_id;
                $m->obj_type = $obj_type;
                $m->resource_id = $r->id;
                $m->save();
            }
        }
    }

    //更新收藏量
    public static function updateCollectionQuantity($id)
    {
        $rows = !is_array($id)?array($id):$id;
        foreach ($rows as $article_id) {
            DB::select('update `cms_article` set collection_quantity=(select count(id) from `t_user_article_collections` 
              where article_id='.$article_id.') where id='.$article_id);
        }
    }

}
